#include <stm8s_tim1.h>

void TIM1_EncoderInterfaceConfig(TIM1_EncoderMode_TypeDef TIM1_EncoderMode,
                                 TIM1_ICPolarity_TypeDef TIM1_IC1Polarity,
                                 TIM1_ICPolarity_TypeDef TIM1_IC2Polarity)
{
  /* Check the parameters */
  assert_param(IS_TIM1_ENCODER_MODE_OK(TIM1_EncoderMode));
  assert_param(IS_TIM1_IC_POLARITY_OK(TIM1_IC1Polarity));
  assert_param(IS_TIM1_IC_POLARITY_OK(TIM1_IC2Polarity));
  
  /* Set the TI1 and the TI2 Polarities */
  if (TIM1_IC1Polarity != TIM1_ICPOLARITY_RISING)
  {
    TIM1->CCER1 |= TIM1_CCER1_CC1P;
  }
  else
  {
    TIM1->CCER1 &= (uint8_t)(~TIM1_CCER1_CC1P);
  }
  
  if (TIM1_IC2Polarity != TIM1_ICPOLARITY_RISING)
  {
    TIM1->CCER1 |= TIM1_CCER1_CC2P;
  }
  else
  {
    TIM1->CCER1 &= (uint8_t)(~TIM1_CCER1_CC2P);
  }
  /* Set the encoder Mode */
  TIM1->SMCR = (uint8_t)((uint8_t)(TIM1->SMCR & (uint8_t)(TIM1_SMCR_MSM | TIM1_SMCR_TS))
                         | (uint8_t) TIM1_EncoderMode);
  
  /* Select the Capture Compare 1 and the Capture Compare 2 as input */
  TIM1->CCMR1 = (uint8_t)((uint8_t)(TIM1->CCMR1 & (uint8_t)(~TIM1_CCMR_CCxS)) 
                          | (uint8_t) CCMR_TIxDirect_Set);
  TIM1->CCMR2 = (uint8_t)((uint8_t)(TIM1->CCMR2 & (uint8_t)(~TIM1_CCMR_CCxS))
                          | (uint8_t) CCMR_TIxDirect_Set);
}

/**
  * @brief  Configures the TIM1 Prescaler.
  * @param   Prescaler specifies the Prescaler Register value
  * This parameter must be a value between 0x0000 and 0xFFFF
  * @param   TIM1_PSCReloadMode specifies the TIM1 Prescaler Reload mode.
  * This parameter can be one of the following values
  * - TIM1_PSCRELOADMODE_IMMEDIATE: The Prescaler is loaded immediately.
  * - TIM1_PSCRELOADMODE_UPDATE: The Prescaler is loaded at the update event.
  * @retval None
  */
